#include "myclient.h"
#include <QHostAddress>
#include "mytask.h"
MyClient::MyClient(QObject *parent) :
    QObject(parent)
{
    QThreadPool::globalInstance()->setMaxThreadCount(20);
    //mytask = NULL;
    socket = NULL;
}

void MyClient::SetSocket(int Descriptor)
{
    socket = new QTcpSocket();
    //socket = sock;
    socket->setSocketDescriptor(Descriptor);
    connect(socket,SIGNAL(connected()),this,SLOT(comeconnected()));
    connect(socket,SIGNAL(disconnected()),this,SLOT(newdisconnected()));
    connect(socket,SIGNAL(readyRead()),this,SLOT(readyRead()));
    QString str = QObject::tr("hello : %1:").arg(Descriptor);
    socket->write(str.toLocal8Bit());
    socket->flush();
    socket->waitForBytesWritten(10);
}

void MyClient::comeconnected()
{
    qDebug()<<"client connected event";
}

void MyClient::newdisconnected()
{
    qDebug()<<"client disconnected event";

}

void MyClient::readyRead()
{
    QString ip = socket->peerAddress().toString();
    qDebug()<<ip+":"+socket->readAll();

    MyTask* mytask = new MyTask();
    mytask->setAutoDelete(true);
    connect(mytask,SIGNAL(Result(int)),this,SLOT(TaskResult(int)),Qt::DirectConnection);
    QThreadPool *pool = QThreadPool::globalInstance();
    pool->start(mytask);
    qDebug()<<"active thread count:"<<pool->activeThreadCount();

}

void MyClient::TaskResult(int Number)
{
    //    QByteArray Buffer;
    //    Buffer.append("Result = ");
    //    Buffer.append(QString::number(Number));
    //    socket->write(Buffer);
    //    socket->waitForBytesWritten(30000);
}
